package com.website.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.website.common.util.WebUtil;
import com.yufeixuan.captcha.utils.CaptchaUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 登陆认证，添加验证码验证和记住我的授权
 *
 * @author zhangshuw
 * @date 2017/7/9
 */
@Slf4j
@Setter
public class MyFormAuthenticationFilter extends FormAuthenticationFilter{

	private String validAuthCode;

    public MyFormAuthenticationFilter(String validAuthCode){
        this.validAuthCode = validAuthCode;
    }
	@Override
	protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        request.setAttribute(getFailureKeyAttribute(), ae);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //允许记住我作为已授权
        return super.isAccessAllowed(request, response, mappedValue) || SecurityUtils.getSubject().isRemembered();
    }

    @Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                if(!"false".equalsIgnoreCase(validAuthCode)){
                    Session session = SecurityUtils.getSubject().getSession(false);
                	if(session == null || !CaptchaUtil.ver(WebUtils.getCleanParam(request, "captcha"),
                            WebUtils.toHttp(request))){
                		setFailureAttribute(request, new AuthenticationException("验证码错误"));
                		return true;
                	}
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            if(WebUtil.isAjax(request)){
            	JSONObject jo = new JSONObject();
				jo.put("msg", "请登录后重试");
				jo.put("success", false);
				response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
				response.getWriter().write(jo.toString());
				return false;
            }else{
            	saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }
}
